package com.example.tests;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;

import java.util.Random;

import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import com.example.obj.ContactObject;
import com.example.obj.ContactSet;

public class Test_07_ContactModification extends TestBase{
	
	Random rnd = new Random();
	
	@BeforeMethod
	public void init(){
		if (manager.getContactHelper().getContactsCache().size() == 0) { 
			log.info("Before: Start contact modification");
			log.info("There are no contacts for modification. Try to create one");
			manager.getContactHelper().createContact(new ContactObject().setFirstName("name"));
		}
	}
	
	@Test(priority = 3)
	public void testContactCanBeModified() throws Exception {
		log.info("Start testContactCanBeModified");
		ContactObject modifiedContact = new ContactObject()
			.setFirstName("contEDITFirstName")
			.setLastName("contEDITLastName")
			.setAddress("contEDITAddress")
			.setPhoneHome("222")
			.setPhoneMobile("222")
			.setPhoneWork("222")
			.setEmail("mailEDIT@domain.ru")
			.setEmail2("mail2EDIT@domain.ru")
			.setBday("1")
			.setBmonth("January")				
			.setByear("2013")
			.setAddress2("contEDITAddress")
			.setPhone2("222");		
		ContactSet oldContactSet = manager.getContactHelper().getContactsCache();
		assertThat(oldContactSet.size() > 0, is(true));
		log.info("Old contacts list: " + oldContactSet);
		ContactObject oldContact = oldContactSet.getElement(rnd.nextInt(oldContactSet.size()));		
		manager.getContactHelper().modifyContact(oldContact.id, modifiedContact);		
		ContactSet newContactSet = manager.getContactHelper().getContactsCache();	
		log.info("New contacts list: " + newContactSet);
		log.info("Start assertions: size, lists' elements");		
		assertThat(newContactSet.size(), equalTo(oldContactSet.size()));
		assertThat(newContactSet, equalTo(oldContactSet.without(oldContact).with(modifiedContact)));
		log.info("Stop assertions");
	}

	@AfterMethod
	public void testUIConfirmWithDB(){
		log.info("After testContactCanBeModified");
		ContactSet contactsDB = manager.getContactHelper().getContactsCache();
		ContactObject contactDB = contactsDB.getElement(rnd.nextInt(contactsDB.size()));		
		log.info("Contact from DB: " + contactDB);
		ContactObject contactUI = manager.getContactHelper().getContactUI(contactDB.id);
		log.info("Contact from UI: " + contactUI);
		assertThat(contactUI, equalTo(contactDB));
	}
}
